<template>
  <el-dialog title="选择设备" :visible.sync="visible" width="1200px" top="5vh" append-to-body>
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="设备名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入设备名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
      <!-- <el-form-item style="float: right">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="createNewMedia" >新增媒体文件</el-button>
      </el-form-item> -->
    </el-form>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="mediaList"
      row-key="id"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column label="设备名称" align="center" prop="name" />
      <el-table-column label="终端状态" align="center" prop="status" />
      <el-table-column label="所属区域" align="center" prop="prisonRoomName" />
      <el-table-column label="操作" width="200"  align="center">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleSelect(scope.row)"
            :disabled="isSelected(scope.row.id)"
          >添加</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <div style="margin: 20px 0 10px">
      已选择的设备：
      <div style="margin: 10px 0">
        <el-tag
          style="margin-right: 10px;"
          v-for="tag in rtnMedias"
          :key="tag.name"
          closable
          @close="closeTag"
          type="info">
          {{tag.name}}
        </el-tag>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="handleSelectDevice">确 定</el-button>
      <el-button @click="visible = false">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { listDevice } from "@/api/system/device";
  import { getToken } from '@/utils/auth'
  export default {
    dicts: ['midea_file_type', 'media_audio_type', 'media_type'],
    data() {
      const validateVoice = (rule, value, callback) => {
        if (!this.newMediaData.fileId&& this.newMediaData.fileType === '01') {
          callback(new Error('请上传音频文件'))
        } else {
          callback()
        }
      }
      //文本转语音规则
      const validateContent = (rule, value, callback) => {
        if (value === '' && this.newMediaData.fileType === '02') {
          callback(new Error('请输入文本内容'));
        } else {
          callback();
        }
      }
      return {
        // 遮罩层
        loading: true,
        // 显示搜索条件
        showSearch: true,
        // 表格树数据
        mediaList: [],
        rtnMedias:[],
        // 弹出层标题
        title: "",
        visible:false,
        // 是否显示弹出层
        open: false,
        // 重新渲染表格状态
        refreshTable: true,
        ids:null,
        // 查询参数
        queryParams: {
          name: '',
          pageNum: 1,
          pageSize: 10,
        },
        // 总条数
        total: 0,
        // 表单参数
        form: {},
        playMedia:false,
        videoSrc:'',
        creatMedia:false,
        newMediaData:{
          fileType:'02'
        },
        fileList:[],
        rules: {
          type: [
            { required: true, message: "广播类型 1、日常广播 2、紧急广播 3、实时广播不能为空", trigger: "change" }
          ],
          name: [
            { required: true, message: "广播任务名称不能为空", trigger: "blur" }
          ],
          content:[
            {validator: validateContent, trigger: 'blur'}
          ],
          fileId:[
            {validator: validateVoice, trigger: 'change' }
          ]
        },
        uploadURL: process.env.VUE_APP_BASE_API+'/system/files?module=MEDIA',
        token:''
      };
    },
    created() {
      this.token = 'Bearer ' + getToken();
    },
    computed:{
      isSelected(){
        return (id)=>{
          let index = this.rtnMedias.findIndex(i=>i.id===id);
          if(index>-1)return true;
          return  false;
        }
      }
    },
    watch: {
      playMedia(v){
        if(!v){
          this.$refs['audio'].pause()
        }
      },
      creatMedia(){
        this.resetForm("creatForm");
        this.fileList = [];
        this.newMediaData = {
          type:'',
          name:'',
          fileType:'02',
          audioType:1,
          content:''
        }
      }
    },
    methods: {
      // 显示弹框
      show() {
        this.rtnMedias = []
        this.getList();
        this.visible = true;
      },
      /** 查询流媒体列表 */
      getList() {
        this.loading = true;
        listDevice(this.queryParams).then(response => {
          this.mediaList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },

      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      handleSelectDevice(){
        if(this.rtnMedias.length<=0)
        {
          this.$modal.msgError("最少选择一行数据");
          return;
        }
        this.$emit("selectDone",this.rtnMedias)
        this.visible = false
      },
      handlePlay(id){
        this.videoSrc =getVoice(id)+'&t='+new Date().getTime();
        this.playMedia = true;
      },
      handleSelect(item){
        this.rtnMedias.push(item)
      },
      closeTag(item){
        let index = this.rtnMedias.findIndex(i=>i.id===item.id);
        this.rtnMedias.splice(index,1)
      },
      createNewMedia(){
        this.creatMedia = true;
      },
      handleRemove(){
        this.newMediaData.fileId = '';
      },
      uploadSuccess(res){
        this.$set(this.newMediaData,'fileId',res.data.id)
        this.$refs["creatForm"].clearValidate('fileId')
      },
      submitNewMedia(){
        console.log(this.newMediaData)
        this.$refs["creatForm"].validate(valid => {
          if (valid) {
            if(this.newMediaData.fileType==='01'){
              //音频上传
              delete this.newMediaData.content;
              delete this.newMediaData.audioType;
            }else if(this.newMediaData.fileType==='02'){
              //文本转语音
              delete this.newMediaData.fileId;
            }
            addMedia(this.newMediaData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.creatMedia = false;
              this.getList();
            });
          }
        });
      },

    }
  };
</script>
